package com.r2coding.article.service.impl;

import com.github.pagehelper.PageHelper;
import com.r2coding.article.entity.ArticleEntity;
import com.r2coding.article.feign.SystemFeignService;
import com.r2coding.article.model.CommentUser;
import com.r2coding.article.service.ArticleService;
import com.r2coding.article.to.User;
import com.r2coding.article.vo.req.CommentReqVo;
import com.r2coding.article.vo.resp.AdminCommentRespVo;
import com.r2coding.article.vo.resp.CommentRespVo;
import com.r2coding.article.vo.resp.CommentVo;
import com.r2coding.article.vo.resp.CommentsRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.r2coding.common.util.PageUtils;
import com.r2coding.common.util.Query;

import com.r2coding.article.dao.CommentDao;
import com.r2coding.article.entity.CommentEntity;
import com.r2coding.article.service.CommentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 评论信息表
 *
 * @author 98k灬
 * @email hk666zx@163.com
 * @date 2022-04-13 19:34:16
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {
    @Autowired
    SystemFeignService systemFeignService;

    @Autowired
    ArticleService articleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CommentEntity> page = this.page(
                new Query<CommentEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    public void saveComment(CommentEntity comment) {
        // 根据评论用户id查询评论用户信息
        User commentUser = systemFeignService.getById(comment.getCommentUserId());
        if (commentUser != null) {
            comment.setCommentUserAvatar(commentUser.getAvatar());
            comment.setCommentUserName(commentUser.getUserName());
        }

        // 根据被评论用户id查询被评论用户信息
        User targetUser = systemFeignService.getById(comment.getTargetUserId());
        if (targetUser != null) {
            comment.setTargetUserAvatar(targetUser.getAvatar());
            comment.setTargetUserName(targetUser.getUserName());
        }

        comment.setCreateTime(new Date());
        this.baseMapper.insert(comment);
    }

    @Override
    public CommentRespVo commentInfo(Integer articleId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CommentRespVo resp = new CommentRespVo();
        QueryWrapper<CommentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);
        wrapper.orderByDesc("create_time");
        List<CommentEntity> list = this.baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<CommentVo> comments = list.stream().map( item -> {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(item, commentVo);
            commentVo.setCreateDate(sdf.format(item.getCreateTime()));
            return  commentVo;
        }).collect(Collectors.toList());

        List<CommentVo> list1 = new ArrayList<>();
        for (CommentVo entity : comments) {
            if (entity.getParentId().equals(0)) {
                list1.add(entity);
            }
        }
        for (CommentVo entity : list1) {
            childrenComment(comments, entity);
        }
        this.childrenList(list1);
        comments.removeIf(next -> !next.getParentId().equals(0));
        resp.setComments(comments);
        resp.setCount(comments.size());
        return resp;
    }

    private List<CommentVo> childrenList(List<CommentVo> list) {
        if (!CollectionUtils.isEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                // 封装评论用户的用户信息
                CommentUser commentUser = new CommentUser();
                commentUser.setId(list.get(i).getCommentUserId());
                commentUser.setNickName(list.get(i).getCommentUserName());
                commentUser.setAvatar(list.get(i).getCommentUserAvatar());
                list.get(i).setCommentUser(commentUser);
                CommentUser targetUser = new CommentUser();
                targetUser.setId(list.get(i).getTargetUserId());
                targetUser.setNickName(list.get(i).getTargetUserName());
                targetUser.setAvatar(list.get(i).getTargetUserAvatar());
                list.get(i).setTargetUser(targetUser);
                this.childrenList(list.get(i).getChildrenList());
            }
        }
        return list;
    }


    @Transactional
    @Override
    public void deleteComment(Integer id) {
        QueryWrapper<CommentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        // 删除该评论的所有子评论
        this.baseMapper.delete(wrapper);
        // 删除该评论
        this.baseMapper.deleteById(id);
    }


    @Override
    public AdminCommentRespVo comments(CommentReqVo req) {
        AdminCommentRespVo respVo = new AdminCommentRespVo();
        Integer count = this.baseMapper.selectCount(null);
        respVo.setTotal(count);
        PageHelper.startPage(req.getCurrent(), req.getSize());
        List<CommentEntity> commentList = this.baseMapper.selectList(new QueryWrapper<CommentEntity>().orderByDesc("create_time"));
        if (!CollectionUtils.isEmpty(commentList)) {
            List<CommentsRespVo> collect = commentList.stream().map(item -> {
                CommentsRespVo commentsRespVo = new CommentsRespVo();
                commentsRespVo.setId(item.getId())
                        .setCommentUserAvatar(item.getCommentUserAvatar())
                        .setTargetUserAvatar(item.getTargetUserAvatar())
                        .setCommentUserName(item.getCommentUserName())
                        .setTargetUserName(item.getTargetUserName())
                        .setCreateTime(item.getCreateTime())
                        .setContent(item.getContent());
                // 根据文章id查询文章信息
                ArticleEntity article = articleService.getById(item.getArticleId());
                commentsRespVo.setArticleTitle(article.getTitle());
                return commentsRespVo;
            }).collect(Collectors.toList());
            respVo.setList(collect);
        }
        return respVo;
    }

    private CommentVo childrenComment(List<CommentVo> commentList, CommentVo comment) {
        List<CommentVo> children = new ArrayList<>();
        for (CommentVo m : commentList) {
            if (m.getParentId().equals(comment.getId())) {
                children.add(childrenComment(commentList, m));
            }
        }
        comment.setChildrenList(children);
        return comment;
    }

    @Override
    public List<CommentEntity> getByArticleId(Integer articleId) {
        return null;
    }

    private CommentEntity childrenComment(List<CommentEntity> menuList, CommentEntity comment) {
        return null;
    }
}